﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using YiShop.Framework.Config;

namespace YiShop.Framework.JwtBearer
{
    /// <summary>
    /// JWT加解密
    /// </summary>
    public class JWTEncryption
    {
        /// <summary>
        /// 获取基于JWT的Token
        /// </summary>
        /// <param name="claims">需要在登陆的时候配置</param>
        /// <param name="permissionRequirement">在startup中定义的参数</param>
        /// <returns></returns>
        public static string BuildJwtToken(Claim[] claims)
        {
            var now = DateTime.Now;
            var signingKey = Encoding.ASCII.GetBytes(AppSettings.JWTSettings.IssuerSigningKey);
            var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(signingKey), SecurityAlgorithms.HmacSha256);
            // 实例化JwtSecurityToken
            var jwt = new JwtSecurityToken(
                claims: claims,
                notBefore: now,
                expires: now.Add(TimeSpan.FromMinutes(AppSettings.JWTSettings.ExpiredTime)),
                signingCredentials: signingCredentials
            );
            // 生成 Token
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            return encodedJwt;
        }
        /// <summary>
        /// 读取 Token，不含验证
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static JwtSecurityToken SecurityReadJwtToken(string accessToken)
        {
            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            var jwtSecurityToken = jwtSecurityTokenHandler.ReadJwtToken(accessToken);
            return jwtSecurityToken;
        }

    }

}
